<script setup lang='ts'>
import { useAdgroupList, getSnapshotList } from '@fl/api/advertising-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { SearchTable, SearchForm } from '@fl/components'
import type { VxePagerEvents } from 'vxe-table'

const visible = defineModel<boolean>('visible', { required: true })
const emits = defineEmits(['confirmChoose'])

const timeVisible = ref<boolean>(false) // 选择分期弹框
const title = ref<string>('选择广告组')
const title2 = ref<string>('选择分期')
const timeList = ref<any>()
const currentTime = ref<number>(0)
const selectGroupSnapshotId = ref<number>()

const initialState = {
    activeStatus: undefined,
    name: '',
}
const state = ref(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

const params = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    ...state.value,
}))

const list = ref<any>([])

const { data, isLoading } = useAdgroupList(params)
watchEffect(() => {
    if (data.value) {
        list.value = cloneDeep(data.value.rows).reduce((pre, cur) => {
            cur.activeStatus = cur.activeStatus === 1 ? 1 : 0
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = data.value.total!
        console.log('list.value', list.value)
    }
})

// 提交
async function submit() {
    timeCancel()
    cancel()
    emits('confirmChoose', selectGroupSnapshotId.value)
}

function cancel() {
    visible.value = false
}

function reset() {
    visible.value = false
}

function timeCancel() {
    timeVisible.value = false
}

function timeReset() {
    timeVisible.value = false
}

function getTimeList(id) {
    getSnapshotList({
        groupId: id,
    }).then((data) => {
        // data有数据说明已存在广告排期
        if (data.length) {
            timeList.value = data.map(item => ({
                ...item,
                activeTime: [item.activeStart, item.activeEnd],
            }))
            selectTime(0, timeList.value[0])
        }
        else {
            timeList.value = [{
                activeTime: [],
                groupId: id.value,
            }]
        }
    }).catch(() => {
        
    })
}

// 选择分期
function selectTime(index, item) {
    currentTime.value = index
    selectGroupSnapshotId.value = item.id
    console.log('selectGroupSnapshotId', selectGroupSnapshotId.value)
}

// 选择此组
function adConfig(row) {
    console.log('row', row)
    timeVisible.value = true
    getTimeList(row.id)
}

function submitSearch(values) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const columns = [
    {
        colProps: {
            span: 6,
        },
        label: '搜索关键词',
        prop: 'name',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '活动状态',
        options: [
            {
                label: '未开始',
                value: '0',
            },
            {
                label: '进行中',
                value: '1',
            },
        ],
        prop: 'activeStatus',
        valueType: 'select',
    },

]

const gridOptions = reactive({
    columns: [
        { field: 'name', title: '广告名称' },
        { field: 'contentQuantity', title: '内容数量', width: 80 },
        { field: 'platform', title: '平台类型' },
        { field: 'createTime', title: '创建时间' },
        { field: 'creator', title: '操作人' },
        { field: 'remark', title: '备注' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '状态' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 100 },
    ],
})
</script>

<template>
    <PlusDialog v-model="visible" :title="title" width="1000" close-on-press-escape :has-footer="false" @cancel="cancel"
        @closed="reset">
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="resetSearch"
                    @submit="submitSearch"
        />
        <div class="table">
            <SearchTable v-bind="gridOptions"
                            v-model:pager="tablePage"
                            :loading="isLoading"
                            :data="list"
                            @page-change="handlePageChange"
            >
                <template #activeStatus="{ row }">
                    <div>{{ row.activeStatus === 1 ? '进行中': '未开始' }}</div>
                </template>
                <template #operate="{ row }">
                    <div class="operate-btns">
                        <el-button type="primary"
                                    text
                                    @click="adConfig(row)"
                        >
                            选择此组
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </div>
    </PlusDialog>

    <PlusDialog v-model="timeVisible" :title="title2" width="400" close-on-press-escape :has-footer="false" @cancel="timeCancel"
        @closed="timeReset">
        <div class="ad-by-stages">
            <div v-for="(item, index) in timeList" :key="item.adTime" class="time-item">
                <div :class="currentTime === index ? 'ad-time-piker active' : 'ad-time-piker'">
                    <el-date-picker v-model="item.activeTime" type="datetimerange" start-placeholder="开始日期"
                        end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                         disabled />

                    <span :class="currentTime === index ? 'sort active' : 'sort'" @click="selectTime(index, item)">
                        {{ index + 1 }}
                    </span>
                </div>
            </div>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="timeCancel">
                取消
            </el-button>

            <!-- :loading="isPending" -->
            <SubmitBtn type="primary" @click="submit">
                提交
            </SubmitBtn>
        </div>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.table {
    height: 600px;
}
.ad-by-stages {
    // height: 400px;
    display: flex;
    flex-wrap: wrap;
    .time-item {
        display: flex;
        width: 310px;
        margin-bottom: 12px;
        margin-left: 40px;

        :deep(.ad-time-piker) {
            display: flex;
            align-items: center;
            position: relative;

            >.sort {
                position: absolute;
                left: 0;
                top: 0;
                width: 30px;
                height: 32px;
                display: block;
                font-size: 16px;
                line-height: 32px;
                border-right: 1px solid #e6ebf5;
                text-align: center;
                cursor: pointer;

                &.active {
                    color: var(--el-color-primary);
                    border-right: 1px solid var(--el-color-primary);
                }
            }

            &.active {
                .el-range-editor.el-input__wrapper {
                    border: 1px solid var(--el-color-primary);
                }
            }
        }

        :deep(.el-range-editor.el-input__wrapper) {
            width: 260px;
            padding-left: 40px;
        }

        .icon-btns {
            display: flex;
            align-items: center;
            margin-left: 10px;

            .el-icon {
                font-size: 18px;
                cursor: pointer;

                &.add {
                    color: var(--el-color-primary);
                    margin-right: 6px;
                }
            }
        }
    }
}
</style>
